// 课程表管理系统 - 主页面JavaScript（干净版本）

// 全局变量
let currentTab = 'class';
let classes = [];
let teachers = [];

// 分页状态
let classPage = {
    current: 1,
    per_page: 20,
    total: 0,
    pages: 0,
    search: '',
    year: '',
    semester: '',
    college: ''
};

let teacherPage = {
    current: 1,
    per_page: 20,
    total: 0,
    pages: 0,
    search: '',
    department: '',
    semester: ''
};

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始初始化...');
    
    // 绑定标签页切换事件
    bindTabEvents();
    
    // 绑定搜索事件
    bindSearchEvents();
    
    // 加载初始数据
    loadClasses(1);
    loadTeachers(1);
    
    console.log('初始化完成');
});

// 绑定标签页切换事件
function bindTabEvents() {
    const classTab = document.getElementById('class-tab');
    const teacherTab = document.getElementById('teacher-tab');
    
    if (classTab) {
        classTab.addEventListener('click', function() {
            switchTab('class');
        });
    }
    
    if (teacherTab) {
        teacherTab.addEventListener('click', function() {
            switchTab('teacher');
        });
    }
}

// 切换标签页
function switchTab(tab) {
    currentTab = tab;
    
    // 更新标签状态
    document.querySelectorAll('.nav-link').forEach(link => {
        link.classList.remove('active');
    });
    document.getElementById(`${tab}-tab`).classList.add('active');
    
    // 更新内容显示
    document.querySelectorAll('.tab-pane').forEach(pane => {
        pane.classList.remove('show', 'active');
    });
    document.getElementById(`${tab}-pane`).classList.add('show', 'active');
    
    // 更新总数显示
    updateTotalCount();
}

// 绑定搜索事件
function bindSearchEvents() {
    console.log('绑定搜索事件...');
    
    // 班级搜索
    const classSearchBtn = document.getElementById('classSearchBtn');
    const classClearFilter = document.getElementById('classClearFilter');
    
    if (classSearchBtn) {
        console.log('绑定班级搜索按钮');
        classSearchBtn.addEventListener('click', function(e) {
            e.preventDefault();
            console.log('班级搜索按钮被点击');
            searchClasses();
        });
    }
    
    if (classClearFilter) {
        classClearFilter.addEventListener('click', function(e) {
            e.preventDefault();
            clearClassFilters();
        });
    }
    
    // 教师搜索
    const teacherSearchBtn = document.getElementById('teacherSearchBtn');
    const teacherClearFilter = document.getElementById('teacherClearFilter');
    
    if (teacherSearchBtn) {
        console.log('绑定教师搜索按钮');
        teacherSearchBtn.addEventListener('click', function(e) {
            e.preventDefault();
            console.log('教师搜索按钮被点击');
            searchTeachers();
        });
    }
    
    if (teacherClearFilter) {
        teacherClearFilter.addEventListener('click', function(e) {
            e.preventDefault();
            clearTeacherFilters();
        });
    }
    
    // 回车搜索
    const searchInputs = [
        'classSearchInput', 'classYearFilter', 'classSemesterFilter', 'classCollegeFilter',
        'teacherSearchInput', 'teacherDepartmentFilter', 'teacherSemesterFilter'
    ];
    
    searchInputs.forEach(inputId => {
        const input = document.getElementById(inputId);
        if (input) {
            input.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    if (inputId.startsWith('class')) {
                        searchClasses();
                    } else {
                        searchTeachers();
                    }
                }
            });
        }
    });
    
    console.log('搜索事件绑定完成');
}

// 班级搜索
function searchClasses() {
    console.log('执行班级搜索');
    
    const searchInput = document.getElementById('classSearchInput');
    const yearFilter = document.getElementById('classYearFilter');
    const semesterFilter = document.getElementById('classSemesterFilter');
    const collegeFilter = document.getElementById('classCollegeFilter');
    
    classPage.search = searchInput ? searchInput.value.trim() : '';
    classPage.year = yearFilter ? yearFilter.value.trim() : '';
    classPage.semester = semesterFilter ? semesterFilter.value.trim() : '';
    classPage.college = collegeFilter ? collegeFilter.value.trim() : '';
    
    console.log('班级搜索参数:', classPage);
    loadClasses(1, true);
}

// 清除班级筛选
function clearClassFilters() {
    console.log('清除班级筛选');
    
    const inputs = ['classSearchInput', 'classYearFilter', 'classSemesterFilter', 'classCollegeFilter'];
    inputs.forEach(inputId => {
        const input = document.getElementById(inputId);
        if (input) input.value = '';
    });
    
    classPage.search = '';
    classPage.year = '';
    classPage.semester = '';
    classPage.college = '';
    
    loadClasses(1, true);
}

// 教师搜索
function searchTeachers() {
    console.log('执行教师搜索');
    
    const searchInput = document.getElementById('teacherSearchInput');
    const departmentFilter = document.getElementById('teacherDepartmentFilter');
    const semesterFilter = document.getElementById('teacherSemesterFilter');
    
    teacherPage.search = searchInput ? searchInput.value.trim() : '';
    teacherPage.department = departmentFilter ? departmentFilter.value.trim() : '';
    teacherPage.semester = semesterFilter ? semesterFilter.value.trim() : '';
    
    console.log('教师搜索参数:', teacherPage);
    loadTeachers(1, true);
}

// 清除教师筛选
function clearTeacherFilters() {
    console.log('清除教师筛选');
    
    const inputs = ['teacherSearchInput', 'teacherDepartmentFilter', 'teacherSemesterFilter'];
    inputs.forEach(inputId => {
        const input = document.getElementById(inputId);
        if (input) input.value = '';
    });
    
    teacherPage.search = '';
    teacherPage.department = '';
    teacherPage.semester = '';
    
    loadTeachers(1, true);
}

// 加载班级数据
async function loadClasses(page = 1, resetPage = false) {
    try {
        if (resetPage) {
            classPage.current = 1;
            page = 1;
        }
        
        console.log('加载班级数据，页码:', page);
        
        // 构建查询参数
        const params = new URLSearchParams({
            page: page,
            per_page: classPage.per_page
        });
        
        if (classPage.search) params.append('search', classPage.search);
        if (classPage.year) params.append('year', classPage.year);
        if (classPage.semester) params.append('semester', classPage.semester);
        if (classPage.college) params.append('college', classPage.college);
        
        const response = await fetch(`/api/classes?${params}`);
        console.log('班级API响应状态:', response.status);

        if (response.ok) {
            const result = await response.json();
            console.log('班级API响应数据:', result);

            if (result.success) {
                classes = result.data;
                classPage.current = result.page;
                classPage.total = result.total;
                classPage.pages = result.pages;
                console.log(`成功加载班级数据: ${classes.length} 个班级，共 ${classPage.total} 个，第 ${classPage.current}/${classPage.pages} 页`);
                
                renderClasses();
                renderClassPagination();
                updateTotalCount();
            } else {
                console.error('加载班级数据失败:', result.error);
                showNoData('class');
            }
        } else {
            console.error('加载班级数据失败，HTTP状态:', response.status);
            showNoData('class');
        }
    } catch (error) {
        console.error('加载班级数据时出错:', error);
        showNoData('class');
    }
}

// 加载教师数据
async function loadTeachers(page = 1, resetPage = false) {
    try {
        if (resetPage) {
            teacherPage.current = 1;
            page = 1;
        }
        
        console.log('加载教师数据，页码:', page);
        
        // 构建查询参数
        const params = new URLSearchParams({
            page: page,
            per_page: teacherPage.per_page
        });
        
        if (teacherPage.search) params.append('search', teacherPage.search);
        if (teacherPage.department) params.append('department', teacherPage.department);
        if (teacherPage.semester) params.append('semester', teacherPage.semester);
        
        const response = await fetch(`/api/teachers?${params}`);
        console.log('教师API响应状态:', response.status);
        
        if (response.ok) {
            const result = await response.json();
            console.log('教师API响应数据:', result);
            
            if (result.success) {
                teachers = result.data;
                teacherPage.current = result.page;
                teacherPage.total = result.total;
                teacherPage.pages = result.pages;
                console.log(`成功加载教师数据: ${teachers.length} 个教师，共 ${teacherPage.total} 个，第 ${teacherPage.current}/${teacherPage.pages} 页`);
                
                renderTeachers();
                renderTeacherPagination();
                updateTotalCount();
            } else {
                console.error('加载教师数据失败:', result.error);
                showNoData('teacher');
            }
        } else {
            console.error('加载教师数据失败，HTTP状态:', response.status);
            showNoData('teacher');
        }
    } catch (error) {
        console.error('加载教师数据时出错:', error);
        showNoData('teacher');
    }
}

// 渲染班级列表
function renderClasses() {
    const classList = document.getElementById('classList');
    const noClassData = document.getElementById('noClassData');

    if (!classList) return;

    if (classes.length === 0) {
        classList.innerHTML = '';
        if (noClassData) noClassData.style.display = 'block';
        return;
    }

    if (noClassData) noClassData.style.display = 'none';

    let html = '';
    classes.forEach(cls => {
        html += `
            <div class="col-md-6 col-lg-4 mb-3 class-card">
                <div class="card h-100 shadow-sm" style="cursor: pointer;" onclick="viewClassSchedule('${cls.class_id}')">
                    <div class="card-body d-flex flex-column">
                        <h6 class="card-title text-primary mb-2">
                            <i class="bi bi-people-fill me-2"></i>
                            ${cls.class_name}
                        </h6>
                        <div class="card-text flex-grow-1">
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="bi bi-hash me-1"></i>
                                    班级ID: ${cls.class_id}
                                </small>
                            </div>
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="bi bi-calendar-event me-1"></i>
                                    学期: ${cls.semester}
                                </small>
                            </div>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mt-auto">
                            <span class="badge bg-primary rounded-pill">
                                <i class="bi bi-book me-1"></i>
                                ${cls.schedule_count} 门课程
                            </span>
                            <small class="text-muted">
                                <i class="bi bi-arrow-right"></i>
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });

    classList.innerHTML = html;
}

// 渲染教师列表
function renderTeachers() {
    const teacherList = document.getElementById('teacherList');
    const noTeacherData = document.getElementById('noTeacherData');

    if (!teacherList) return;

    if (teachers.length === 0) {
        teacherList.innerHTML = '';
        if (noTeacherData) noTeacherData.style.display = 'block';
        return;
    }

    if (noTeacherData) noTeacherData.style.display = 'none';

    let html = '';
    teachers.forEach(teacher => {
        html += `
            <div class="col-md-6 col-lg-4 mb-3 teacher-card">
                <div class="card h-100 shadow-sm" style="cursor: pointer;" onclick="viewTeacherSchedule('${teacher.teacher_id}')">
                    <div class="card-body d-flex flex-column">
                        <h6 class="card-title text-success mb-2">
                            <i class="bi bi-person-badge-fill me-2"></i>
                            ${teacher.teacher_name}
                        </h6>
                        <div class="card-text flex-grow-1">
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="bi bi-hash me-1"></i>
                                    工号: ${teacher.teacher_id}
                                </small>
                            </div>
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="bi bi-building me-1"></i>
                                    部门: ${teacher.department}
                                </small>
                            </div>
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="bi bi-award me-1"></i>
                                    职称: ${teacher.teacher_title}
                                </small>
                            </div>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mt-auto">
                            <span class="badge bg-info rounded-pill">
                                <i class="bi bi-book me-1"></i>
                                ${teacher.schedule_count} 门课程
                            </span>
                            <small class="text-muted">
                                <i class="bi bi-arrow-right"></i>
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });

    teacherList.innerHTML = html;
}

// 渲染班级分页
function renderClassPagination() {
    const paginationContainer = document.getElementById('classPagination');
    if (!paginationContainer) return;

    if (classPage.pages <= 1) {
        paginationContainer.innerHTML = '';
        return;
    }

    let html = '<nav><ul class="pagination justify-content-center">';

    // 上一页
    if (classPage.current > 1) {
        html += `<li class="page-item">
            <a class="page-link" href="#" onclick="loadClasses(${classPage.current - 1}); return false;">上一页</a>
        </li>`;
    }

    // 页码
    const startPage = Math.max(1, classPage.current - 2);
    const endPage = Math.min(classPage.pages, classPage.current + 2);

    for (let i = startPage; i <= endPage; i++) {
        const activeClass = i === classPage.current ? 'active' : '';
        html += `<li class="page-item ${activeClass}">
            <a class="page-link" href="#" onclick="loadClasses(${i}); return false;">${i}</a>
        </li>`;
    }

    // 下一页
    if (classPage.current < classPage.pages) {
        html += `<li class="page-item">
            <a class="page-link" href="#" onclick="loadClasses(${classPage.current + 1}); return false;">下一页</a>
        </li>`;
    }

    html += '</ul></nav>';

    // 添加页面信息
    html += `<div class="text-center text-muted mt-2">
        显示第 ${(classPage.current - 1) * classPage.per_page + 1} - ${Math.min(classPage.current * classPage.per_page, classPage.total)} 条，共 ${classPage.total} 条记录
    </div>`;

    paginationContainer.innerHTML = html;
}

// 渲染教师分页
function renderTeacherPagination() {
    const paginationContainer = document.getElementById('teacherPagination');
    if (!paginationContainer) return;

    if (teacherPage.pages <= 1) {
        paginationContainer.innerHTML = '';
        return;
    }

    let html = '<nav><ul class="pagination justify-content-center">';

    // 上一页
    if (teacherPage.current > 1) {
        html += `<li class="page-item">
            <a class="page-link" href="#" onclick="loadTeachers(${teacherPage.current - 1}); return false;">上一页</a>
        </li>`;
    }

    // 页码
    const startPage = Math.max(1, teacherPage.current - 2);
    const endPage = Math.min(teacherPage.pages, teacherPage.current + 2);

    for (let i = startPage; i <= endPage; i++) {
        const activeClass = i === teacherPage.current ? 'active' : '';
        html += `<li class="page-item ${activeClass}">
            <a class="page-link" href="#" onclick="loadTeachers(${i}); return false;">${i}</a>
        </li>`;
    }

    // 下一页
    if (teacherPage.current < teacherPage.pages) {
        html += `<li class="page-item">
            <a class="page-link" href="#" onclick="loadTeachers(${teacherPage.current + 1}); return false;">下一页</a>
        </li>`;
    }

    html += '</ul></nav>';

    // 添加页面信息
    html += `<div class="text-center text-muted mt-2">
        显示第 ${(teacherPage.current - 1) * teacherPage.per_page + 1} - ${Math.min(teacherPage.current * teacherPage.per_page, teacherPage.total)} 条，共 ${teacherPage.total} 条记录
    </div>`;

    paginationContainer.innerHTML = html;
}

// 显示无数据状态
function showNoData(type) {
    if (type === 'class') {
        const classList = document.getElementById('classList');
        const noClassData = document.getElementById('noClassData');
        if (classList) classList.innerHTML = '';
        if (noClassData) noClassData.style.display = 'block';
    } else {
        const teacherList = document.getElementById('teacherList');
        const noTeacherData = document.getElementById('noTeacherData');
        if (teacherList) teacherList.innerHTML = '';
        if (noTeacherData) noTeacherData.style.display = 'block';
    }
}

// 更新总数显示
function updateTotalCount() {
    const totalCountElement = document.getElementById('totalCount');
    if (!totalCountElement) return;

    if (currentTab === 'class') {
        totalCountElement.textContent = `共 ${classPage.total || 0} 个班级`;
    } else {
        totalCountElement.textContent = `共 ${teacherPage.total || 0} 个教师`;
    }
}

// 查看班级课程表
function viewClassSchedule(classId) {
    console.log('查看班级课程表:', classId);
    window.location.href = `/class/${classId}`;
}

// 查看教师课程表
function viewTeacherSchedule(teacherId) {
    console.log('查看教师课程表:', teacherId);
    window.location.href = `/teacher/${teacherId}`;
}
